String, Array, Map, List, Set

#Kotlin #Kotlin_Tips

1. 초기화

List

//immutable list
val list1: List<Int> = listOf(1, 2, 3)
val list2: List<Int> = emptyList<Int>()
val list3: List<Int> = listOfNotNull(1, 2, 3, null, 4, 5, null) // 1, 2, 3, 4, 5

//mutable list
val list4: MutableList<Int> = mutableListOf(1, 2)
val list5: MutableList<Int> = MutableList<Int>(3){1}

Array

//IntArray, Array<Int>
val array1: IntArray = IntArray(3){1} //3개짜리 배열을 1로 초기화 //int[] in JVM
val array2: IntArray = intArrayOf(1, 1, 1)
val array3: Array<Int> = Array<Int>(3){1} //Integer[] in JVM
val array4: Array<Int> = Array<Int>(3){it*1} //it은 인덱스


//기타 
val array5: CharArray = charArrayOf('a', 'b', 'c')
val array6: LongArray = longArrayOf(0L, 1L, 2L)
val array7: Array<String> = Array<String>(2){"Hello", "Hi"} // String은 stringArrayOf가 없음
val array8: Array<Int> = arrayOf(1, 2, 3) // 타입추론

Map

// immutable
val map1: Map<Int, Int> = mapOf(0 to 1, 1 to 2, 2 to 3)

// mutable
val map2: MutableMap<Int, Int> = mutableMapOf()
val map3: MutableMap<Int, Int> = mutableMapOf(0 to 1, 1 to 2, 2 to 3)

Set

// immutable
val set1: Set<Int> = setOf(0, 1, 2, 3)

// mutable
val set2: MutableSet<Int> = mutableSetOf()
val set3: MutableSet<Int> = mutableSetOf(1, 2, 3)

2. 형변환

List -> Array

val list: List<String> = listOf("one", "two", "three", "four")
val listToArray: Array<String> = list.toTypedArray()

IntArray & Array

// IntArray -> Array<Int>
val intArray: IntArray = IntArray(3){1}
val intArrayToArray: Array<Int> = intArray.toTypedArray()

// Array<Int> -> IntArray
val arrayInt: Array<Int> = Array<Int>(3){1}
val arrayIntToIntArray: IntArray = arrayInt.toIntArray()

Map & MutableMap

// Map -> MutableMap
val map: Map<Int, Int> = mapOf(0 to 1, 1 to 2, 2 to 3)
val mapToMutableMap: MutableMap<Int, Int> = map.toMutableMap()

// MutableMap -> Map
val mutableMap: MutableMap<Int, Int> = mutableMapOf(0 to 1, 1 to 2, 2 to 3)
val mutableMapToMap: Map<Int, Int> = mutableMap.toMap()

List & MutableList

val list: List<Int> = listOf(1, 2, 3)
val listToMutableList: MutableList<Int> = list.toMutableList()

val mutableList: MutableList<Int> = mutableListOf(1, 2)
val mutableListToList: List<Int> = mutableList.toList()

3. 기타

String을 split한 리턴값은 List

fun CharSequence.split(
    vararg delimiters: String,
    ignoreCase: Boolean = false,
    limit: Int = 0
): List<String>

List의 Sublist

val list1: List<Int> = listOf(1, 2, 3, 4, 5, 6, 7)

//List.subList(inclusiveInt: Int, exclusiveInt: Int)
val subList: List<Int> = list1.subList(0, 2)//[1, 2] 

Array의 SubArray

val array1: Array<Int> = arrayOf(1, 2, 3, 4, 5, 6)

// inclusive, inclusive
val subArray1: Array<Int> = array1.sliceArray(0..3) 
// IntRange(inclusiveInt: Int, inclusiveInt: Int)
val subArray2: Array<Int> = array1.sliceArray(IntRange(0, 3))